import { YeeRouter } from "../types";
import Router = require("koa-router");

export const apiMapIndex = new Map();

/**
 * 注册路由
 * @export
 * @param {YeeRouter} yeeRouter
 * @returns
 */
export function registerHandleApi(yeeRouter: YeeRouter) {
  const router = new Router;

  let yeePrefix = yeeRouter.prefix ? yeeRouter.prefix : '';

  if(yeePrefix && !yeePrefix.includes('/')) {
    yeePrefix = '/' + yeePrefix;
  }
  
  router.prefix(yeePrefix);

  yeeRouter.router.map(api => {

    let yeePath = api.path;

    if(yeePath && !yeePath.includes('/')) {
      yeePath = '/' + yeePath;
    }

    router[api.method as any](yeePath, api.controller);
    
    const path = yeePrefix + yeePath;
    if( apiMapIndex.has(`${api.method} ${path}`) ){
      throw new Error(`路由名称 ${path} 重复 ${JSON.stringify(yeeRouter)}`);
    }else{
      apiMapIndex.set(`${api.method} ${path}`, api);
    }
  })

  return router;
}

